package com.heima.admin.interceptor;

import com.heima.model.admin.pojos.AdUser;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AdminThreadLocalUtil;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * Author: Administrator
 * CreateTime: 2024/10/9
 * Project: heima-leadnews
 */
public class AdminTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String userId = request.getHeader("userId");
        Optional<String> optional = Optional.ofNullable(userId);
        if(optional.isPresent()){
            //把用户id存入threadloacl中
            AdUser adUser = new AdUser();
            adUser.setId(Integer.valueOf(userId));
            AdminThreadLocalUtil.setUser(adUser);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        AdminThreadLocalUtil.clear();
    }
}
